const app = getApp()

Page({
  data: {
    foods: [null, null],
    nutritionItems: [
      { name: '热量', key: 'calories', unit: 'kcal', color: '#ff9c6e' },
      { name: '蛋白质', key: 'protein', unit: 'g', color: '#7ABD82' },
      { name: '脂肪', key: 'fat', unit: 'g', color: '#ffd666' },
      { name: '碳水化合物', key: 'carbs', unit: 'g', color: '#5cdbd3' },
      { name: '膳食纤维', key: 'fiber', unit: 'g', color: '#b37feb' },
      { name: '糖', key: 'sugar', unit: 'g', color: '#ff85c0' },
      { name: '钠', key: 'sodium', unit: 'mg', color: '#69c0ff' }
    ]
  },

  onLoad() {
    this.updateNutritionBars()
  },

  selectFood(e) {
    const index = e.currentTarget.dataset.index
    wx.navigateTo({
      url: `/pages/food/selector?mode=compare&index=${index}`
    })
  },

  removeFood(e) {
    const index = e.currentTarget.dataset.index
    const foods = [...this.data.foods]
    foods[index] = null
    this.setData({ foods })
    this.updateNutritionBars()
  },

  // 从食物选择器页面返回时接收选中的食物
  onShow() {
    if (this.data.selectedFood !== undefined && this.data.compareIndex !== undefined) {
      const foods = [...this.data.foods];
      foods[this.data.compareIndex] = this.data.selectedFood;
      
      this.setData({
        foods,
        selectedFood: undefined,
        compareIndex: undefined
      });
      
      this.updateNutritionBars();
    }
  },

  // 更新营养成分对比条
  updateNutritionBars() {
    if (!this.data.foods[0] || !this.data.foods[1]) return

    const nutritionItems = this.data.nutritionItems.map(item => {
      const value1 = this.data.foods[0][item.key]
      const value2 = this.data.foods[1][item.key]
      const maxValue = Math.max(value1, value2)
      
      return {
        ...item,
        leftWidth: (value1 / maxValue) * 100,
        rightWidth: (value2 / maxValue) * 100
      }
    })

    this.setData({ nutritionItems })
  }
}) 